import React from 'react';
import { inject, observer } from 'mobx-react';
import {
  WeaLocaleProvider, WeaRightMenu
  , WeaTop, WeaTab, WeaFormItem, WeaSearchGroup, WeaDialog,WeaAlertPage
} from 'ecCom';
import { WeaTableNew, WeaSwitch } from 'comsMobx';
import { toJS } from 'mobx';
import { Button, Modal } from 'antd';
import { isEmpty } from 'lodash';
import { getFields } from '../apis/monitor';
import { WeaLogView } from 'comsMobx';
// import {com} from 'weaWorkplan';
// const WorkPlanCreate = com.WorkPlanCreate;
import WorkPlanCreate from '../../../pc4mobx/workplan/public/workPlanCreate/index';
import { filterBR } from '../util/util';
const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
const WeaLogViewComp = WeaLogView.Component;

@inject('monitorStore')
@observer
class Monitor extends React.Component {

  componentWillMount() {
    const { monitorStore } = this.props;
    const { getMonitor, getCondition } = monitorStore;
    getMonitor();
    getCondition();
  }

  componentWillReceiveProps(nextProps) {
    const { monitorStore } = this.props;
    const { getMonitor , form} = monitorStore;
    if (this.props.location.key !== nextProps.location.key) {
      form&&getMonitor(form.getFormParams());      
    }
  }

  componentWillUnmount(){
    const { monitorStore } = this.props;
    monitorStore.showSearchAd = false;
  }

  operation = (method) => {
    const { monitorStore } = this.props;
    let { selectedRowKeys, operation,exportAll } = monitorStore;
    selectedRowKeys = toJS(selectedRowKeys)
    if(method == 'finish' || method == 'delete'){
      !isEmpty(selectedRowKeys) && Modal.confirm({
        title: method === 'finish' ? getLabel(384633, '是否确定强制完成?') : getLabel(15097, "确定要删除吗?"),
        onOk: () => operation({ workPlanIDs: selectedRowKeys.join(','), method: method }),
      });
    }else if(method == 'export'){
      exportAll();
    }
    
  }

  getButtons = () => {
    const { monitorStore } = this.props;
    const { selectedRowKeys, selectedRows } = monitorStore;
    const disabled = isEmpty(toJS(selectedRowKeys));
    let disabledNow = true;
    toJS(selectedRows).forEach(v => {
      if (v.status === '0') disabledNow = false;//选中的值有待办事宜
    })
    const btns = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@wdtol6@doDelete`} type='primary' disabled={disabled} onClick={() => this.operation('delete')}>{getLabel(131966, '删除')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@nidddc@doFinish`} type='primary' disabled={disabledNow || disabled} onClick={() => this.operation('finish')}>{getLabel(384651, '强制完成')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@tuut9i@doExportAll`} type='primary' onClick={() => this.operation('export')}>{getLabel(81272,'导出全部')}</Button>
    ]
    return btns;
  }

  getButtonsData = () => {
    const { monitorStore } = this.props;
    const { selectedRowKeys, selectedRows, tableStore, getMonitor, setState } = monitorStore;
    const disabled = isEmpty(toJS(selectedRowKeys));
    let disabledNow = true;
    toJS(selectedRows).forEach(v => {
      if (v.status === '0') disabledNow = false;//选中的值有待办事宜
    })
    const btns = [
      {
        key: 'delete',
        content: getLabel(131966, '删除'),
        icon: <i className='icon-coms-delete' />,
        disabled: disabled,
        onClick: () => this.operation('delete')
      }, {
        key: 'finish',
        content: getLabel(384651, '强制完成'),
        icon: <i className='icon-coms-Approval' />,
        disabled: disabledNow || disabled,
        onClick: () => this.operation('finish')
      },{
        key: 'export',
        content: getLabel(81272,'导出全部'),
        icon: <i className='icon-coms-download' />,
        onClick: () => this.operation('export')
      }, {
        key: 'search',
        content: getLabel(197,'搜索'),
        icon: <i className='icon-coms-search' />,
        disabled: false,
        onClick: () => getMonitor()
      },
      {
        key: 'column',
        content: getLabel(32535,"显示列定制"),
        icon: <i className='icon-coms-Custom' />,
        disabled: false,
        onClick: () => {
          tableStore.setColSetVisible(true);
          tableStore.tableColSet(true);
        }
      },
      {
        key: 'log',
        content: getLabel(83,'日志'),
        icon: <i className='icon-coms-Print-log' />,
        disabled: false,
        onClick: () => setState({ visibleLog: true })
      }
    ];
    return btns;
  }

  onEnterSearch = () => {
    const { monitorStore } = this.props;
    const { setState, getMonitor, form } = monitorStore;
    getMonitor(form.getFormParams());
    setState({ showSearchAd: false });
  }

  getSearchs = () => {
    const { monitorStore } = this.props;
    const { condition, form, setState, getMonitor } = monitorStore;
    const { isFormInit } = form;
    let group = [];
    const formParams = form.getFormParams();
    isFormInit && toJS(condition).map((c, _index) => {
      let items = [];
      c.items.map(fields => {
        if (fields.isQuickSearch) {
          this.quickSearchPara = fields.domkey[0];
        }
        items.push({
          com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@rvvujq@${fields.domkey[0]}`}
            label={`${fields.label}`}
            labelCol={{ span: `${fields.labelcol}` }}
            wrapperCol={{ span: `${fields.fieldcol}` }}>
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@cuwni2@${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} onEnterSearch={this.onEnterSearch} />
          </WeaFormItem>),
          colSpan: 1
        })
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@yobf6n@${_index}`} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />)
    });
    return group;
  }

  getTabButtonsAd = () => {
    const { monitorStore } = this.props;
    const { form, setState, getMonitor } = monitorStore;
    const btns = [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@24oq0s@doSearch`} type='primary' onClick={() => {
        getMonitor(form.getFormParams());
        setState({ showSearchAd: false });
      }}>{getLabel(197, '搜索')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@f3w0bz@doReset`} type='ghost' onClick={() => { form.reset(); getMonitor(form.getFormParams()); }}>{getLabel(2022, '重置')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8jyz8n@doCancel`} type='ghost' onClick={() => setState({ showSearchAd: false })}>{getLabel(31129, '取消')}</Button>];
    return btns;
  }

  onOperatesClick = (record, index, operate) => {
    const { monitorStore } = this.props;
    const { operation } = monitorStore;
    if (operate.index === '0') {
      Modal.confirm({
        title: getLabel(384633, '是否确定强制完成?'),
        onOk: () => operation({ workPlanIDs: record.ID, method: 'finish' }),
      });
    }
  }

  getColumns = (columns) => {
    const { monitorStore } = this.props;
    const { setState } = monitorStore;
    let newColumns = '';
    newColumns = columns.map(column => {
      let newColumn = column;
      newColumn.render = (text, record, index) => { //前端元素转义
        let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
        if(valueSpan) {// 过滤br
          valueSpan = filterBR(valueSpan);
        }
        return (
          newColumn.dataIndex == 'ID' ?
            <a className="workplan-title" onClick={() => setState({ visibleCreate: true, workPlanId: record.ID })} dangerouslySetInnerHTML={{ __html: valueSpan }} />
            :
            <div dangerouslySetInnerHTML={{ __html: valueSpan }} />
        )
      }
      return newColumn;
    });
    return newColumns;
  }

  //变更Tab页
  changeData= (theKey) => {
    const {monitorStore} = this.props;
    const { showSearchAd, setState, form, getMonitor} = monitorStore;
    form.updateFields(this.quickSearchPara, true);
    setState({ showSearchAd: false,loading: true, timeSag: theKey});
    getMonitor({timeSag: theKey})
    
  }

  getRowSelection = () => {
    const { monitorStore } = this.props;
    const { setState, selectedRowKeys, selectedRows } = monitorStore;
    return {
      selectedRowKeys: toJS(selectedRowKeys),
      selectedRows: toJS(selectedRows),
      onChange: (selectedRowKeys, selectedRows) => {
        setState({ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows });
      }
    };
  }

  render() {
    const { monitorStore } = this.props;
    const { tableStore, showSearchAd, setState, selectedRowKeys
      , form, getMonitor, selectedRows, workPlanId, visibleCreate, timeSag
      , activeKey, visibleLog, logStore,alertPage ,close, onlyClose,loading,logType,logSmallType} = monitorStore;

    const topTab = [
      {
        groupid: 'all',
        title: `${getLabel(332,'全部')}`,
        viewcondition: '0'
      },
      {
        groupid: 'today',
        title: `${getLabel(15537,'今天')}`,
        viewcondition: '1'
      },
      {
        groupid: 'theWeek',
        title: `${getLabel(15539,'本周')}`,
        viewcondition: '2'
      },
      {
        groupid: 'theMon',
        title: `${getLabel(130018,'本月')}`,
        viewcondition: '3'
      },
      {
        groupid: 'local',
        title: `${getLabel(21904,'本季')}`,
        viewcondition: '4'
      },
      {
        groupid: 'theYear',
        title: `${getLabel(126760,'本年')}`,
        viewcondition: '5'
      },
    ]

    return (
      <div className='wea-workplanengine-monitor'>
      {
        alertPage ?
            <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@a5bk83`}>
              <div>{getLabel(382663, '暂无权限')}</div>
            </WeaAlertPage>
            :
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@e00ijt`}
          datas={this.getButtonsData()}
          collectParams={{
            favname: getLabel(19792, '日程监控'),
            favouritetype: 5,
            objid: 0,
            importantlevel: 1,
          }}>
          <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@x9e7tk`}
            title={getLabel(19792, '日程监控')}
            loading={loading}
            icon={<i className='icon-coms-schedule' />}
            iconBgcolor='#7734ff'
            showDropIcon
            buttons={this.getButtons()}
            dropMenuDatas={this.getButtonsData()}
            dropMenuProps={{
              collectParams: {
                favname: getLabel(19792, '日程监控'),
                favouritetype: 5,
                objid: 0,
                importantlevel: 1,
              }
            }}>
            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@ydom1x`}
              searchType={['base', 'advanced']}
              buttonsAd={this.getTabButtonsAd()}
              searchsAd={this.getSearchs()}
              searchsBaseValue={form.getFormParams()[this.quickSearchPara] || ''}
              showSearchAd={showSearchAd}
              setShowSearchAd={() => setState({ showSearchAd: !showSearchAd })}
              hideSearchAd={() => setState({ showSearchAd: false })}
              onSearchChange={value => form.updateFields({ 
                [this.quickSearchPara]: { value }
              })}
              onSearch={() => getMonitor(form.getFormParams())} 
              selectedKey={timeSag}
              datas = {topTab}
              keyParam="viewcondition"
              countParam="groupid"
              onChange={this.changeData.bind(this)}

            />

            <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@jcvpd3`}
              comsWeaTableStore={tableStore}
              hasOrder
              needScroll
              showmethod
              onOperatesClick={this.onOperatesClick}
              getColumns={this.getColumns}
              selectedRowKeys={selectedRowKeys}
              rowSelection={this.getRowSelection()} />
            <WorkPlanCreate ecId={`${this && this.props && this.props.ecId || ''}_WorkPlanCreate@74w8df`}
              type={'preview'}
              visible={visibleCreate}
              doClose={this.workPlanCreateDoClose}//关闭回调, 保存等按钮会自动调用该回调，可以在这里写一些页面的刷新操作
              onlyClose={this.workPlanCreateOnlyClose}//关闭回调,关闭/取消等按钮会自动调用该回调，只做关闭操作
              workPlanId={workPlanId}
              activeKey={activeKey}
              changeTab={this.workPlanCreateChangeTab}
              // onlyClose={() => setState({ visibleCreate: false, activeKey: '1' })}
              close={this.workPlanCreateClose} />
            <WeaLogViewComp ecId={`${this && this.props && this.props.ecId || ''}_WeaLogViewComp@f3nety`} visible={visibleLog} logStore={logStore} logType={logType} logSmallType={logSmallType} 
              onCancel={this.getWeaLogviewCancel} />
          </WeaTop>
        </WeaRightMenu>
        }
      </div>
    
    )
  }

  getWeaLogviewCancel = () => {
    const { monitorStore } = this.props;
    const { setState } = monitorStore;
    setState({ visibleLog: false });
  }

  workPlanCreateDoClose = () => {
    const { monitorStore } = this.props;
    const { close, form } = monitorStore;
    close();
    monitorStore.getMonitor(form.getFormParams()); 
  }

  workPlanCreateOnlyClose = () => {
    const { monitorStore } = this.props;
    const {  onlyClose, setState } = monitorStore;
    onlyClose();
    setState({ visibleCreate: false, activeKey: '1' })
  }

  workPlanCreateChangeTab = (activeKey) => {
    const { monitorStore } = this.props;
    const { setState } = monitorStore;
    setState({ activeKey });
  }

  workPlanCreateClose = () => {
    const { monitorStore } = this.props;
    const { setState } = monitorStore;
    setState({ visibleCreate: false, activeKey: '1' });
  }

}

export default Monitor
